#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import json
import requests
import datetime

from wingman import logger
from wingman.common.error import ErrorCode


class DingTalk:
    """dingTalk发送消息"""

    def get_send(self, token, title, message):
        """
        通过钉钉机器人发送内容
        @param date_str:
        @param msg:
        @param at_all:
        @return:
        """

        if isinstance(message, dict):
            message_str = ""
            for key, value in message.items(): 
                if key != "num_hits" or key != "num_matches":
                    message_str =  message_str + "> " + str(key).replace("#", "") + ":" + value + "\n\n"
        else:
            message_str = message

        markdown = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": f"# {title} \n\n---\n\n {message_str} \n\n---\n\n {str(datetime.datetime.now())}"
            },
            "at": {
                "atDingtalkIds": [ "userid" ],
            }
        }
        text = {
            "msgtype": "text",
            "text": {
                "content": title + "\n" + message_str + str(datetime.datetime.now())
            },
            "at": {
                "isAtAll": "False"
            },
        }
        link = {
            "msgtype": "link",
            "link": {
                "title": "卡片标题",                        # 	卡片的标题,最多不超过64个字符
                "text": "卡片内容",                         # 卡片的内容,最多不超过1024个字符
                "btn_text": "按钮文字",                     # 卡片底部按钮的文字,最多不超过6个字符
                "btn_url": "https://www.example.com",       # 	卡片底部按钮的跳转链接,最长不超过2048个字符
                "is_at_all": False,                         # 是否@所有人,默认为false
                "is_single": False,                         # 是否单聊模式,默认为false
                "at_mobiles": ["手机号码"],                 # @指定手机号的用户列表,最多不超过10个
                "at_users": ["用户名"],                     # 	@指定用户的列表,最多不超过10个 
                "at_party_ids": ["群组ID"],                 # @指定群组的ID列表,最多不超过10个
                "at_discussions": ["讨论组ID"],             # 	@指定讨论组的ID列表,最多不超过10个
                "at_stared": ["已置顶群组或讨论组ID"],          # 	@指定已置顶的群组或讨论组的ID列表,最多不超过10个   
                "at_mentioned": ["被@的用户"],              # @被@的用户列表,最多不超过10个
                "is_hidden": False,                     # 是否隐藏卡片,默认为false
                "ext": {"key": "value"}                 # 扩展字段,用于传递额外的信息,最多不超过5个
            }
        }
        action_card = {
            "msgtype": "action_card",
            "action_card": {
                "title": title ,
                "markdown": '#### ' + title + '\n\n---\n' + message_str + '\n---\n' + str(datetime.datetime.now()) ,
                "single_title": "查看详情",
                "single_url": "https://open.dingtalk.com"
            }
        }
        url = 'https://oapi.dingtalk.com/robot/send?access_token=' + token
        headers = {'Content-Type': 'application/json;charset=utf-8'}

        try:
            request = requests.post(url, headers=headers, data=json.dumps(markdown))
            result = request.text
            # logger.info(ErrorCode.SUCCESS.value, result, __name__)
        except requests.exceptions.RequestException as e:
            result = str(e)
            logger.error(ErrorCode.DING_REQUESTS.value, result, __name__)
        except Exception as e:
            result = str(e)
            logger.error(ErrorCode.DING_REQUESTS.value, result, __name__)
        finally:
            return result


if __name__ == '__main__':
    dd = DingTalk()
    title = "title"
    token = "8eee12b207509c897dc79258dadd64fc1e63f10020a145af2ec2bd947c88de49"
    text = "这是一条测试消息"
    print(dd.get_send(token, text, title))
